/**
 @Name：用户管理
 @Author：tao
 */

layui.define(['table', 'form'], function (exports) {
	var $ = layui.jquery,
		layer = layui.layer;
	var table = layui.table;

	function myUpdate(obj, callback) {
		//'编辑'按钮的回调
		var tr = $(obj.tr);
		var data = obj.data;
		var dialog = $('#Dialog');
		var name = dialog.find('input[name="name"]')[0];
		var type = dialog.find('input[name="type"]')[0];
		var teacherid = dialog.find('input[name="teacherid"]')[0];

		//弹窗, 包含'yes'和'success'两个回调函数
		layer.open({
			type: 1,
			title: '修改课程信息',
			content: dialog,
			area: ['550px', '350px'],
			btn: ['确定', '取消'],
			resize: false,
			yes: function (index, layero) {
				//弹窗'确定'按钮的回调
				//获取iframe元素的值
				name = name.value;
				teacherid = teacherid.value;
				type = type.value;

				layer.close(index);
				//判断弹窗的数据是是否修改 
				if ((data.name != name ||
					data.type != type || data.teacherid != teacherid) &&
					(name && type && teacherid)) {
					data = {
						id: data.id,
						// number: data.number,
						name: name && name != data.name ? name : data.name,
						teacherid: teacherid && teacherid != data.teacherid ? teacherid : data.teacherid,
						type: type && type != data.type ? type : data.type
					}

					callback && callback(data)
					//发起数据修改请求	
				}
			}
			//弹窗弹出后的回调
			,
			success: function (layero, index) {
				//将行的数据传到弹窗
				name.value = data.name;
				type.value = data.type;
				teacherid.value = data.teacherid
			}
		});

	}


	/**
	 * 获取多选框的id, 以及需删除的行对象
	 * @param {object} delData  选择的所有行数据
	 */
	function getDataId(delData) {
		var arr = [];
		for (var i in delData) {
			if (delData[i].checked || !delData[i].hasOwnProperty('checked')) {
				arr.push(delData[i].data.id)
			} else {
				//删checked为false的行
				delete delData[i]
			}
		}
		return {
			delData,
			arr
		}
	}


	function batchadd(callback) {
		var dialog = $('#Dialog');
		var name = dialog.find('input[name="name"]')[0];
		var teacherid = dialog.find('input[name="teacherid"]')[0];
		var type = dialog.find('input[name="type"]')[0];
		layer.open({
			type: 1,
			title: '添加课程',
			content: dialog,
			area: ['550px', '350px'],
			btn: ['确定', '取消'],
			resize: false,
			yes: function (index, layero) {
				layer.close(index)
				//向服务器发起请求  添加数据
				callback && callback({
					name: name.value,
					teacherid: teacherid.value,
					type: type.value
				})
			},
			success: function (layero, index) {
				//将行的数据传到弹窗
				name.value = "";
				teacherid.value = "";
				type.value = "";
			}
		})
	}


	function batchdel(delData, callback) {
		var checkStatus = table.checkStatus('LAY-app-forumreply-list'),
			checkData = checkStatus.data; //得到选中的数据
		if (checkData.length === 0) {
			return layer.msg('请选择数据');
		} else {
			layer.confirm('确定删除吗？', function () {
				callback && callback(getDataId(delData))
			})
		};
	}


	exports('users', {
		getDataId,
		myUpdate,
		batchadd,
		batchdel
	})
});
